// package-order/pages/order-review/index.js
const { navTo, redirectTo, chooseAddress, tipToast, showLoading, hideLoading, subscribeMessage } = require('../../../common/env');
import { WxpayApplymentTipMixins } from '../../../behaviors/page';
import { getCartProductList, clearCartData } from '../../../biztools/cart';
import { createAndPayOrder } from '../../api/order';
import { getOrderOriginInfo, clearOrderOriginInfo } from '../../../biztools/wex';
import { PACKAGE_ORDER_PAGE } from '../../../constants/route';
import { DELIVERY_TYPE_ENUM } from '../../../constants/order';
import { MESSAGE_ID } from '../../../constants/message';
import { invokePlatformPay } from '../../../common/pay';
const { isEmpty } = require('../../../common/utils');
const app = getApp();
Page({
    mixins: [WxpayApplymentTipMixins],
    data: {
        expressTypeEnum: DELIVERY_TYPE_ENUM,
        expressType: DELIVERY_TYPE_ENUM.express,
        addressInfo: {},
        siteInfo: {},
        timeInfo: {},
        remark: '', // 备注
        isAnonymity: false, // 是否匿名
        productList: [],
        orderOriginId: '',
        orderOriginInfo: null,
        totalPrice: 0,
        productTotalPrice: 0,
    },
    onLoad: function (options) {
        const { orderOriginId, shareUserId } = options;
        // 获取保存的活动信息
        const orderOriginInfo = getOrderOriginInfo(orderOriginId);
        const productList = getCartProductList(orderOriginId);
        this.setData({
            orderOriginId,
            orderOriginInfo,
            productList,
            expressType: orderOriginInfo.deliveryModes[0],
            shareUserId: shareUserId ? shareUserId : '',
            siteInfo: orderOriginInfo.warehouses[0],
        }, () => {
            this.calcOrderPrice();
        });
        // 获取活动配置信息
        const that = this;
        // 添加监听
        app.event.addListener('changeSiteInfo', (data) => {
            console.log('OrderReview => 监听到自提点变化', data);
            that.setData({
                siteInfo: data,
            });
        });
    },
    onShow: function () {
    },
    calcOrderPrice: function () {
        const { orderOriginInfo, productList, expressType } = this.data;
        let totalPrice = 0;
        let productTotalPrice = 0;
        for (let i = 0; i < productList.length; i++) {
            const item = productList[i];
            productTotalPrice += item.count * item.selectSku.price;
        }
        if (expressType === DELIVERY_TYPE_ENUM.express) {
            totalPrice += orderOriginInfo.unifiedShippingFee;
        }
        totalPrice += productTotalPrice;
        this.setData({
            totalPrice,
            productTotalPrice,
        });
    },
    // 修改地址
    changeAddress: async function () {
        // navTo(PACKAGE_ORDER_PAGE.selectAddress);
        // 直接使用微信的收货地址
        const addressInfo = await chooseAddress();
        console.log('OrderReview => 选择的地址为：', addressInfo);
        this.setData({
            addressInfo,
        });
    },
    // 修改配送模式
    changeDeliveryType: function (event) {
        this.setData({
            expressType: event.detail,
        }, () => {
            this.calcOrderPrice();
        });
    },
    // 修改自提点
    changePickUpSite: function () {
        const { siteInfo } = this.data;
        let param = {};
        if (!isEmpty(siteInfo)) {
            param = {
                siteId: siteInfo.id
            };
        }
        navTo(PACKAGE_ORDER_PAGE.selectPickupSite);
    },
    // 修改自提时间
    changePickUpTime: function () {},
    // 修改备注
    changeRemark: function (event) {
        this.setData({
            remark: event.detail,
        });
    },
    // 修改匿名状态
    changeAnonymityStatus: function (event) {
        this.setData({
            isAnonymity: event.detail,
        });
    },
    // 订单参数处理
    orderParamsDeal: function () {
        const { expressType, addressInfo, productList } = this.data;
        const isExpress = expressType === DELIVERY_TYPE_ENUM.express;
        if (productList.length === 0) {
            tipToast('购买物品不能为空');
            return false;
        }
        if (isExpress) {
            // 快递
            if (!addressInfo || isEmpty(addressInfo)) {
                tipToast('收货地址不能为空');
                return false;
            }
        } else {
            // 自提
        }
        return true;
    },
    // 下单并支付
    payOrder: async function () {
        const { isAnonymity, orderOriginId, remark, siteInfo, shareUserId, expressType,
            addressInfo, totalPrice, productTotalPrice, productList, orderOriginInfo } = this.data;
        const isExpress = expressType === DELIVERY_TYPE_ENUM.express;
        if (!this.orderParamsDeal()) return;
        if (!this.handleShowWxpayTip({ isWxpayAvailable: orderOriginInfo.isWxpayAvailable })) return;
        showLoading('确认中..');
        const orderParam = {
            shareUserId,
            activityId: orderOriginId,
            brandId: orderOriginInfo.brandId,
            deliveryMode: expressType,
            warehouseId: siteInfo.id,
            shippingAddress: isExpress ? {
                address: addressInfo.address,
                linkman: addressInfo.username,
                mobile: addressInfo.mobile,
            } : {},
            shippingFee: isExpress ? orderOriginInfo.unifiedShippingFee : 0,
            remark,
            productAmount: productTotalPrice,
            amount: totalPrice,
            details: productList.map(item => {
                return {
                    storageKey: item.selectSku.storageKey,
                    productId: item.selectSku.productId,
                    productSpecId: item.selectSku.productSpecId,
                    quantity: item.count,
                    price: item.selectSku.price,
                };
            }),
            isAnonymity,
        };
        // 兑奖订单
        if (orderOriginInfo.awardId) {
            orderParam.awardId = orderOriginInfo.awardId;
        }
        // 生成订单
        const res = await createAndPayOrder(orderParam);
        console.log('OrderReview => 下单结果：', res);
        if (res) {
            hideLoading();
            // 清除本地保存的数据
            // 清除购物车信息
            clearCartData(orderOriginId);
            // 清除保存活动信息
            clearOrderOriginInfo(orderOriginId);
            // 执行支付
            await invokePlatformPay(res.transactionInfo);
            await subscribeMessage([MESSAGE_ID.order_status, MESSAGE_ID.self_pickup]);
            // 跳转到订单详情
            redirectTo(PACKAGE_ORDER_PAGE.orderDetail, {
                orderNumber: res.order.serialNumber,
                showPaySuccess: true,
            })
        }
    },
})